<template>
  <u-modal
    v-model:visible="showPrivacy"
    title="隐私保护指引"
    :showFooter="false"
  >
    <view>
      在使用当前小程序服务之前，请仔细阅读
      <text class="link" @click="openPrivacyContract">{{
        privacyContractName
      }}</text>
      。如果你同意，请点击“同意”开始使用。
    </view>
    <view class="modal-footer">
      <view class="cancel" @click="exitMiniProgram">拒绝</view>
      <view
        id="agree-btn"
        class="confirm"
        open-type="agreePrivacyAuthorization"
        @agreeprivacyauthorization="handleAgreePrivacyAuthorization"
        @click="handleAgreePrivacyAuthorization"
      >
        同意
      </view>
    </view>
  </u-modal>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

const privacyContractName = ref('')
const showPrivacy = ref(false)

onMounted(() => {
  setTimeout(() => {
    privacyContractName.value = uni.getStorageSync('privacyContractName') || ''
    showPrivacy.value = uni.getStorageSync('showPrivacy') || false
    // eslint-disable-next-line no-console
    console.log(privacyContractName.value, 'privacyContractName')
    // eslint-disable-next-line no-console
    console.log(showPrivacy.value, 'showPrivacy')
  }, 1000)
})
// 同意隐私协议
const handleAgreePrivacyAuthorization = () => {
  uni.requirePrivacyAuthorize({
    success: (res) => {
      showPrivacy.value = false
      uni.setStorageSync('showPrivacy', false)
    }
  })
}
// 拒绝隐私协议
const exitMiniProgram = () => {
  uni.showModal({
    content:
      '如果拒绝,我们将无法获取您的信息, 包括手机号、位置信息、相册等该小程序十分重要的功能,您确定要拒绝吗?',
    success: (res) => {
      if (res.confirm) {
        showPrivacy.value = false
        uni.exitMiniProgram({
          success: () => {
            // eslint-disable-next-line no-console
            console.log('退出小程序成功')
          }
        })
      }
    }
  })
}

// 跳转协议页面
// 点击高亮的名字会自动跳转页面 微信封装好的不用操作
const openPrivacyContract = () => {
  uni.openPrivacyContract({
    fail: () => {
      uni.showToast({
        title: '网络错误',
        icon: 'error'
      })
    }
  })
}
</script>

<style lang="scss" scoped>
.link {
  color: #07c160 !important;
  text-decoration: underline !important;
}
.modal-footer {
  position: relative;
  display: flex;
  justify-content: space-between;
  margin-top: 64rpx;
  view {
    flex: 1;
    text-decoration: none;
    position: relative;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 16rpx;
    border: 1px solid rgba(4, 178, 124, 0.6);
    padding: 16rpx 0;
    border-radius: 16rpx;

    & + view {
      margin-left: 24rpx;
    }

    &.cancel {
      color: #04b27c;
    }
    &.confirm {
      background: #04b27c;
      font-weight: bold;
      color: #ffffff;
    }
  }
}
</style>
